Intercepting Touch Events(捕捉触摸事件)
很高兴,我们的程序已经进展了很多,我们添加了随机函数,也添加了摇晃事件。虽然我不是一个设计师,但我们的App进行到现在,我已经觉得屏幕上的预测按钮是多余的了。 但是,我们又不想仅仅通过摇晃这一种方式来预测,那我们应该怎么做呢?是否可以点击屏幕上的水晶球来预测呢? 当然是可以的,我们要做的,就是捕捉到一个点击事件,就像我们捕捉到摇晃事件一样。
首先,我们设计了两张更好看的背景图片,让我们将原来的背景图片替换掉吧。 选中原来的两张背景图片,鼠标右键选择"Delete",在弹出窗口中选择"Move to Trash"(直接删除文件),然后将两张新的背景图添加进水晶球应用("Add Files to "crystal ball"…")
然后点击ViewController.m
文件,在文件最下面,@end之前,加入如下代码:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
predictionLabel.text=@"";
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
NSInteger indexofPredictionArray= arc4random_uniform([self.predictionArray count]);
predictionLabel.text =[self.predictionArray objectAtIndex:indexofPredictionArray];
}
就可以实现通过触摸事件,来做预测了!
现在,我们之前的"predict"按钮就失去原有的意义了,让我们在MainStoryboard.storyboard
中,点击按钮,按下键盘上的"delete"键,将按钮删除,并点击ViewController.h
文件,删除如下代码:
- (IBAction)butoonPressed:(UIButton *)sender;
之后点击ViewController.m
文件,找到buttonPressed
的方法,删除掉整个方法,这样我们就没有多余代码了,运行一下看看是不是按钮消失了呢…
最后一步,因为在捕捉摇晃事件和捕捉触摸事件中,我们都用了下面的这段代码:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
predictionLabel.text=@"";
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
NSInteger indexofPredictionArray= arc4random_uniform([self.predictionArray count]);
predictionLabel.text =[self.predictionArray objectAtIndex:indexofPredictionArray];
}
难免显得有些多余,让我们继续精简一下我们的代码吧。
点击ViewController.h
文件,在@interface
之后加入如下代码:
-(void)makePrediction;
然后点击ViewController.m
文件,在文件最后,@end
之前,加入如下代码:
-(void)makePrediction{
NSInteger indexofPredictionArray= arc4random_uniform([self.predictionArray count]);
predictionLabel.text =[self.predictionArray objectAtIndex:indexofPredictionArray];
}
最后,将motionEnded
方法和touchesEnded
方法中的代码更改为如下代码:
[self makePrediction];
大功告成了,我们的代码目前非常简洁易懂,运行一下,看看功能吧…
{$ activeFileHint $}